import Tablemodel from "../../components/table"
import dayjs from "dayjs"
import customParseFormat from "dayjs/plugin/customParseFormat"
import "./style.less"
import React, { useCallback, useEffect, useMemo, useState } from "react"
import {
  Select,
  Input,
  Button,
  DatePicker,
  message,
  Upload,
  Form,
  theme,
  Row,
  Col,
  Space,
  Pagination
} from "antd"
import {
  SearchOutlined,
  PlusOutlined,
  UploadOutlined,
  DownloadOutlined,
  DownOutlined
} from "@ant-design/icons"
import { conferenceget, usetype, TypeClass } from "@/api/modules/conference/index"
import { useNavigate } from "react-router-dom"

const { Option } = Select

dayjs.extend(customParseFormat)

const Conference = () => {
  //路由跳转
  const navigate = new useNavigate()

  // 上传实验
  const props = {
    name: "file",
    action: "https://localhost:3666/meeting/importExcel",
    method: "post",
    headers: {
      authorization: "authorization-text"
      // token: JSON.parse(sessionStorage.getItem("token"))
    },
    onChange(info) {
      if (info.file.status !== "uploading") {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === "done") {
        message.success(`${info.file.name} 文件上传成功`)
      } else if (info.file.status === "error") {
        message.error(`${info.file.name} 文件上传失败`)
      }
    }
  }

  //列表数据
  const [data, setdata] = useState([])
  //会议列表获取
  const getList = async (page = current, pagesize = 3, formData) => {
    let data = await conferenceget({ ...formData, page, limit: pagesize })
    // 为列表添加唯一key
    let handleData = data.data.map((item) => {
      item.key = item._id
      return item
    })
    setdata([...handleData])

    settotal(data.total)
    setcurrent(data.page || page)
    setpagesize(data.limit || pagesize)
  }

  //分页处理需信息存储
  const [total, settotal] = useState(10)
  const [pagesize, setpagesize] = useState(3)
  const [current, setcurrent] = useState(1)

  //使用类型列表项
  const [useTypeOption, setUseTypeOption] = useState([])
  //使用类型获取
  const useTypes = async () => {
    const { data } = await usetype()
    setUseTypeOption([...data])
  }

  const fileDownload = async () => {
    await TypeClass()
  }

  // 有接口后放开
  useEffect(() => {
    useTypes()
    getList()
  }, [])

  //新表单区-------------------------------------------------------------
  const [form] = Form.useForm()
  const [expand, setExpand] = useState(false)
  const { token } = theme.useToken()

  const formStyle = {
    maxWidth: "none",
    background: token.colorFillAlter,
    borderRadius: token.borderRadiusLG,
    padding: 24
  }
  const roleSearchColumns = [
    {
      label: "开始时间",
      name: "use_start_time",
      type: "date",
      placeholder: "请选择时间"
    },
    {
      label: "结束时间",
      name: "use_end_time",
      type: "date",
      placeholder: "请选择时间"
    },
    {
      label: "会议名称",
      name: "conference_name",
      type: "input",
      placeholder: "请输入名称"
    },
    {
      label: "申请人",
      name: "apply_name",
      type: "input",
      placeholder: "请输入申请人"
    },
    {
      label: "会议主题",
      name: "conference_theme",
      type: "input",
      placeholder: "请输入主题"
    },
    {
      label: "使用类型",
      name: "use_type",
      type: "selectType",
      placeholder: "请选择使用类型",
      options: []
    },
    {
      label: "申请状态",
      name: "apply_status",
      type: "select",
      placeholder: "请选择申请状态",
      options: [
        {
          title: "预约成功",
          value: "1"
        },
        {
          title: "预约中",
          value: "0"
        }
      ]
    },
    {
      label: "检查状态",
      name: "check_status",
      type: "select",
      placeholder: "请选择检查状态",
      options: [
        {
          title: "正常",
          value: "1"
        },
        {
          title: "异常",
          value: "0"
        }
      ]
    }
  ]

  const onFinish = useCallback(
    (value) => {
      // 从value中过滤出key和value不为undefined的项
      let search = JSON.parse(window.sessionStorage.getItem("search")) || []
      let obj = Object.fromEntries(Object.entries(value).filter((item) => item[1] !== undefined))
      console.log(areObjectsEqual(obj, search))
      if (areObjectsEqual(obj, search)) {
        return false
      } else {
        getList(1, 3, obj)
        sessionStorage.setItem("search", JSON.stringify(obj))
      }
    },
    [getList]
  )
  const onFinishFailed = useMemo(() => onFinish, [onFinish])
  function areObjectsEqual(obj1, obj2) {
    // 检查属性数量是否相等
    const keys1 = Object.keys(obj1)
    const keys2 = Object.keys(obj2)
    if (keys1.length !== keys2.length) {
      return false
    }
    // 检查每个属性的值是否相等
    for (let key of keys1) {
      if (obj1[key] !== obj2[key]) {
        return false
      }
    }
    // 所有属性都相等
    return true
  }

  const getFields = () => {
    const total = roleSearchColumns.length
    const count = expand ? total : 4
    let list = roleSearchColumns.slice(0, count)
    const children = list.map((item, index) => {
      return (
        <Col span={6} key={index}>
          {item.type === "input" && (
            <Form.Item name={item.name} label={item.label} {...item}>
              <Input placeholder={item.placeholder} />
            </Form.Item>
          )}
          {item.type === "select" && (
            <Form.Item name={item.name} label={item.label}>
              <Select placeholder={item.placeholder}>
                {item.options.map((option) => {
                  return (
                    <Option value={option.value} key={option.value}>
                      {option.title}
                    </Option>
                  )
                })}
              </Select>
            </Form.Item>
          )}
          {item.type === "date" && (
            <Form.Item name={item.name} label={item.label} {...item}>
              <DatePicker style={{ width: "100%" }} />
            </Form.Item>
          )}
          {item.type === "selectType" && (
            <Form.Item name={item.name} label={item.label}>
              <Select
                placeholder={item.placeholder}
                options={useTypeOption}
                fieldNames={{
                  label: "type_name",
                  value: "_id"
                }}
              />
            </Form.Item>
          )}
        </Col>
      )
    })
    return [...children]
  }

  //点击搜索时
  const onSearch = () => {
    getList(1, 3, [])
  }

  //分页参数
  const getpage = () => {
    return (
      <Pagination
        total={total || 5}
        showTotal={(total) => `共 ${total} 条数据`}
        pageSize={pagesize || 3}
        current={current || 1}
        style={{
          marginTop: 24,
          float: "right"
        }}
        showSizeChanger
        pageSizeOptions={[3, 6, 10]}
        defaultPageSize={3}
        onChange={(page, pageSize) => {
          getList(page, pageSize, {})
        }}
      />
    )
  }

  return (
    <div className="conference">
      <div className="role-list-title">
        <h3>会议模块</h3>
      </div>
      {/* 新搜索 */}
      <Form form={form} name="advanced_search" style={formStyle} onFinish={onFinish}>
        <Row gutter={6}>{getFields()}</Row>
        <div
          style={{
            textAlign: "right"
          }}
        >
          <Space size="small">
            <Button type="primary" htmlType="submit">
              <SearchOutlined />
              搜索
            </Button>
            <Button
              onClick={() => {
                onSearch({})
                form.resetFields()
              }}
            >
              重置
            </Button>

            {roleSearchColumns.length > 4 && (
              <a
                style={{
                  fontSize: 12
                }}
                onClick={() => {
                  setExpand(!expand)
                }}
              >
                <DownOutlined rotate={expand ? 180 : 0} />
                {expand ? "收起" : "展开"}
              </a>
            )}
          </Space>
        </div>
      </Form>
      {/* 会议室跳转等其他功能 */}
      <div style={{ padding: "24px 0px 54px 0px", width: "100%", position: "relative" }}>
        <Button
          type="primary"
          onClick={() => navigate("/admin/conference/conferenceCreate")}
          style={{ float: "left" }}
        >
          <PlusOutlined />
          会议室申请
        </Button>
        <Button onClick={() => fileDownload()} className="spc_button">
          <DownloadOutlined />
          文件下载
        </Button>
        <Upload {...props} className="spc_button">
          <Button icon={<UploadOutlined />}>文件上传</Button>
        </Upload>
      </div>

      {/* 表格和分页 */}
      <Tablemodel data={data} getList={getList} pagination={getpage}></Tablemodel>
    </div>
  )
}

export default Conference
